<template>
  <div>
    <el-tree :data="menus" :props="defaultProps" @node-click="handleNodeClick" :expand-on-click-node="false"
             show-checkbox node-key="catId" :default-expanded-keys="expandedKey"
             draggable :allow-drop="allowDrop">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level<=2"
            type="text"
            size="mini"
            @click="() => append(data)">
            Append
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)">
            edit
          </el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="catagory">
        <el-form-item label="分类名称">
          <el-input v-model="catagory.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="catagory">
        <el-form-item label="图标">
          <el-input v-model="catagory.icon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="catagory">
        <el-form-item label="计量单位">
          <el-input v-model="catagory.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menus: [],
      //最大层级
      maxLevel: 0,
      //提示框名
      title: "",
      //提交的类型
      dialogType: "",//add or edit
      //控制弹框开关，默认为关闭
      dialogFormVisible: false,
      //catagory的默认值
      catagory: {name: "", parentCid: 0, catLevel: 0, showStatus: 1, sort: 0, catId: null, productUnit: "", icon: ""},
      expandedKey: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
  methods: {
    handleNodeClick(data) {
      console.log(data);
    },
    // 获取数据列表
    getMenus() {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get',
      }).then(data => {
        console.log("成功获取到菜单数据...", data.data)
        this.menus = data.data.data;
      })
    },
    append(data) {
      console.log("调用append")
      this.dialogType = "add";
      this.title = "添加分类";
      this.dialogFormVisible = true;
      //初始化数据
      this.catagory.parentCid = data.catId;
      this.catagory.catLevel = data.catLevel * 1 + 1;
      this.catagory.name = "";
      this.catagory.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
    },
    edit(data) {
      console.log("要修改的数据为：", data);
      this.dialogType = "edit";
      this.title = "修改分类";
      this.dialogFormVisible = true;
      //发送请求获取最新的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({data}) => {
        //请求成功
        console.log("edit返回的数据为：", data);
        this.catagory.name = data.data.name;
        this.catagory.catId = data.data.catId;
        this.catagory.icon = data.data.icon;
        this.catagory.productUnit = data.data.productUnit;
        this.catagory.parentCid = data.data.parentCid;
      })
    },
    //添加菜单
    addCategory() {
      console.log("提交的数据为：", this.catagory);
      this.dialogFormVisible = false;
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.catagory, false)
      }).then(() => {
        this.$message({
          type: 'success',
          message: '新增成功!'
        });
        //重新刷新Menus
        this.getMenus();
        //设置默认展开的菜单
        this.expandedKey = [this.catagory.parentCid];
      })
    },
    //修改三级菜单
    editCategory() {
      //es6语法结构表达式，只发送需要修改的字段到后端
      var {catId, name, icon, productUnit} = this.catagory;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({catId, name, icon, productUnit}, false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
        //关闭弹框
        this.dialogFormVisible = false;
        //重新刷新Menus
        this.getMenus();
        //设置默认展开的菜单
        this.expandedKey = [this.catagory.parentCid];
      })
    },
    submitData() {
      if (this.dialogType === "add") {
        this.addCategory();
      }
      if (this.dialogType === "edit") {
        this.editCategory();
      }
    },
    remove(node, data) {
      console.log("调用remove")
      var ids = [data.catId];
      this.$confirm(`是否要删除菜单【${data.name}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //点击确认后执行
        this.$http({
          url: this.$http.adornUrl("/product/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          console.log("删除成功...")
          //重新刷新Menus
          this.getMenus();
          //设置默认展开的菜单
          this.expandedKey = [node.parent.data.catId];
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //拖拽函数，返回true表示可以拖拽
    allowDrop(draggingNode, dropNode, type) {
      //被拖动的当前节点以及目标节点总层数不能大于3，因为我们只有3层
      console.log(draggingNode, dropNode, type);
      //计算最大的层级
      this.countNodeLevel(draggingNode.data);
      let deep = (this.maxLevel - draggingNode.data.catLevel) + 1;
      console.log("当前节点深度：", deep);
      if (type === "inner") {
        return (deep + dropNode.level) <= 3;
      } else {
        return (deep + dropNode.parent.level) <= 3;
      }
      return true;
    },
    countNodeLevel(node) {
      //找到所有子节点，求出最大深度
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            this.maxLevel = node.children[i].catLevel;
          }
          //递归调用
          this.countNodeLevel(node.children[i]);
        }
      }
    }
  },
  created() {
    this.getMenus();
  }
};

</script>

<style scoped>

</style>
